﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;

namespace SafeNet.InitialDatabase.Repository
{
    public abstract class SessionBuilderBase : ISessionBuilder
    {

        private static ISessionFactory m_SessionFactory;

        public ISession OpenSession()
        {
            return GetSessionFactory().OpenSession();
        }

        public FluentConfiguration GetConfiguration()
        {
            FluentConfiguration conf = Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2005
                            .ConnectionString(c => c.FromConnectionStringWithKey("hibernateConnStr"))
                            .ProxyFactoryFactory("NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle")
                            .CurrentSessionContext("web"))
                .Mappings(m => m.FluentMappings.AddFromAssembly(typeof(SessionBuilderBase).Assembly));

            return conf;
        }

        public ISessionFactory GetSessionFactory()
        {
            if (m_SessionFactory == null)
            {
                m_SessionFactory = GetConfiguration().BuildSessionFactory();
            }

            return m_SessionFactory;
        }

        public abstract ISession CurrentSession
        {
            get;
        }

    }
}
